package com.fl.nj.controller;

import com.fl.nj.entity.DatabaseConfig;
import com.fl.nj.service.DatabaseConfigService;
import com.fl.nj.service.DbInfoService;
import com.fl.nj.util.SchemaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据库管理Controller
 * 提供RESTful API接口，用于管理数据库配置中连接的数据库
 */
@RestController
@RequestMapping("/api/db-management")
public class DatabaseManagementController {
    
    @Autowired
    private DatabaseConfigService databaseConfigService;
    
    @Autowired
    private DbInfoService dbInfoService;
    
    /**
     * 获取指定数据库配置下的所有数据库列表
     * @param dbConfigId 数据库配置ID
     * @param dbName 数据库名称关键词（可选）
     * @param page 页码（可选，默认1）
     * @param pageSize 每页条数（可选，默认10）
     * @return 数据库列表及分页信息
     */
    @GetMapping("/databases/{dbConfigId}")
    public ResponseEntity<Map<String, Object>> getDatabases(
            @PathVariable Long dbConfigId,
            @RequestParam(required = false) String dbName,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            // 获取数据库配置
            DatabaseConfig dbConfig = databaseConfigService.getById(dbConfigId);
            if (dbConfig == null) {
                result.put("success", false);
                result.put("message", "数据库配置不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
            }
            
            // 构建查询参数
            Map<String, Object> params = new HashMap<>();
            params.put("dbConfigId", dbConfigId);
            params.put("dbName", dbName);
            params.put("page", page);
            params.put("pageSize", pageSize);
            
            // 从数据库获取数据库信息列表
            List<Map<String, Object>> databases = new ArrayList<>();
            int total = dbInfoService.getTotal(params);
            
            if (total > 0) {
                // 将DbInfo对象转换为Map，以保持与前端的兼容性
                dbInfoService.getPageList(params).forEach(dbInfo -> {
                    Map<String, Object> dbMap = new HashMap<>();
                    dbMap.put("dbName", dbInfo.getDbName());
                    dbMap.put("dbType", dbInfo.getDbType());
                    dbMap.put("tablesCount", dbInfo.getTablesCount());
                    dbMap.put("createTime", dbInfo.getCreateTime());
                    dbMap.put("syncTime", dbInfo.getSyncTime());
                    dbMap.put("status", dbInfo.getStatus());
                    databases.add(dbMap);
                });
            }
            
            result.put("success", true);
            result.put("data", databases);
            result.put("total", total);
            result.put("page", page);
            result.put("pageSize", pageSize);
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "操作失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
    
    /**
     * 从数据库配置同步数据库信息
     * @param dbConfigId 数据库配置ID
     * @return 同步结果
     */
    @PostMapping("/sync-databases/{dbConfigId}")
    public ResponseEntity<Map<String, Object>> syncDatabasesFromConfig(@PathVariable Long dbConfigId) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 调用服务层方法从数据库配置同步数据库信息
            result = dbInfoService.syncDatabasesFromConfig(dbConfigId);
            
            if ((boolean) result.getOrDefault("success", false)) {
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
            }
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "同步数据库信息失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
    
    /**
     * 同步指定数据库的表结构
     * @param request 请求参数，包含数据库配置ID和数据库名称
     * @return 同步结果
     */
    @PostMapping("/sync-schema")
    public ResponseEntity<Map<String, Object>> syncDatabaseSchema(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 获取请求参数
            Long dbConfigId = Long.parseLong(request.get("dbConfigId").toString());
            String databaseName = request.get("databaseName").toString();
            
            // 获取数据库配置
            DatabaseConfig dbConfig = databaseConfigService.getById(dbConfigId);
            if (dbConfig == null) {
                result.put("success", false);
                result.put("message", "数据库配置不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
            }
            
            // 同步表结构
            // 这里可以调用SchemaUtil中的相关方法来实现表结构的同步
            // 注意：实际实现时需要考虑事务管理和异常处理
            boolean success = SchemaUtil.syncDatabaseSchema(dbConfig, databaseName);
            
            if (success) {
                result.put("success", true);
                result.put("message", "数据库表结构同步成功");
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "数据库表结构同步失败");
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
            }
            
        } catch (NumberFormatException e) {
            result.put("success", false);
            result.put("message", "参数格式错误: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "同步表结构失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
}